/*
 * @lc app=leetcode.cn id=697 lang=typescript
 *
 * [697] 数组的度
 */

// @lc code=start
function findShortestSubArray(nums: number[]): number {
    // 统计频数
    let cache = new Map<number, [number, number, number]>();
    nums.forEach((i, index) => {
        if (cache.has(i)) {
            const [count, head] = cache.get(i)!;
            cache.set(i, [count + 1, head, index]);
        } else {
            cache.set(i, [1, index, index]);
        }
    });

    // 找到最高频数
    let max = 0;
    let maxArr: number[] = [];
    for (const [key, [count]] of cache.entries()) {
        if (count > max) {
            max = count;
            maxArr = [key];
            continue;
        }
        if (count === max) {
            maxArr.push(key);
        }
    }

    // 将最低频数 的 位置和求出数组大小
    const countArr = maxArr.map((i) => {
        const [_, head, tail] = cache.get(i)!;
        return tail - head + 1;
    });
    return Math.min(...countArr);
}
// @lc code=end
